$(function(){
    let fileField = $('#image_upload')
    let fileTableBody = $('#uploaded_image_body')
    let fileDeleteConfirm = new Confirm({
        body:'Are you sure to delete the file?',
        heading:'Confirm',
        confirm_text:'Yes, Delete the file',
        confirm_button_class:'btn-danger',
        modal_dialog_class:'modal-dialog-centered'
    })
    let errorConfirm = new Confirm({
        body:'Incorrect file extension, only mp4, png, jpg, jpeg are supported.',
        heading:'Upload Exception',
        cancel_text:'',
        confirm_text:'OK',
        cancel_button_class:'d-none',
        modal_dialog_class:'modal-dialog-centered'
    })
    // check api url
    let file_arr = []
    let csrf = $('input[name="csrfmiddlewaretoken"]').val()
    function uploadFile(file){
        try{
            let ext = file.name.split('.').pop()
            if (!['mp4','png','jpg','jpeg','bmp'].includes(ext)){
                errorConfirm.show()
                return
            }
        }catch{
            errorConfirm.show()
            return
        }


        let jqForm = $('#fileForm')
        let form = jqForm[0]
        console.log(form)
        let data = new FormData(form)
        // data = {}
        data.append('file',file)
        data.append('user_id',user_id)
        data.append('eform',eform_id)
        // console.log(data.keys())
        $.ajax({
            type: "post",
            url: eformFile_url,
            data: data,
            dataType: "json",
            headers:{
                'X-CSRFToken':csrf
            },
            contentType:false,
            processData: false,
            success: function (response) {
                renderFileUI(response)
            }
        });
    }

    function renderFileUI(res){
        let img = ''
        let urls = `/media/${res.file.split('/media/').pop()}`
        
        if (res.isImage){
            img = `<img src="${urls}" class="" height="100px" alt="">`
        }
        if (res.isVideo){
            img = `<video src="${urls}" class="" height="100px" alt=""></video>`
        }
        let filename = decodeURI(res.file.split('/').pop())
        tr = `
        <tr id="eformFile-${res.id}">
            <td>
                ${img}
                <a href="${urls}" target="_blank">
                    ${filename}
                </a>
            </td>
            <td>
                <input class="form-control file-desc" tpye="text" style="margin-top:30px" target="${res.id}" placeholder="Description"/>
            </td>
            <td style="vertical-align : middle;">
                <button type="button" data-fid="${res.id}" class="btn btn-sm btn-danger delete-eform-file" style="vertical-align : middle;" >DELETE</button>
            </td>
        </tr>
        `
        fileTableBody.append(tr)
    }

    function dropUI(id){
        $(`#eformFile-${id}`).remove()
    }

    function deleteFile(id){
        $.ajax({
            type: "DELETE",
            url: `${eformFile_url}${id}`,
            data: {},
            dataType: "json",
            headers:{
                'X-CSRFToken': csrf
            },
            success: function (response) {
                dropUI(id)
            }
        });
    }

    function updateFileDesc(id,desc,callback){
        $.ajax({
            type: "PATCH",
            url: `${eformFile_url}${id}/`,
            data: {
                desc
            },
            dataType: "json",
            headers:{
                'X-CSRFToken': csrf
            },
            success: function (response) {
                callback(response)
            }
        });
    }
    $(document).on('focusout','.file-desc',function(e){
        let tar = $(this).attr('target')
        if (!tar){
            console.log('Error during updating file description')
            return
        }
        let desc = this.value
        updateFileDesc(tar,desc,_=>console.log('Updated file description'))
    })
    $(document).on('click','.delete-eform-file',function(){
        let id = $(this).data('fid')
        // console.log('>>>>>>>>>>>>>>>',id)
        fileDeleteConfirm.show(_=>{
            deleteFile(id)
        })
        // deleteFile(id)
    })
    // if (!api_url || api_url==""){
    //     console.log(`eformFile url is not rendered`)
    // }

    fileField.on('click', function () {
        console.log('click')
    });

    fileField.on('change',function(e){
        let files = e.target.files
        console.log(files)
        if (files.length){
            // file_arr.push(files[0])
            uploadFile(files[0])
        }
    })


    
  
})